import React from "react";
import {
    Popconfirm,
    List,
    Modal,
    Avatar,
    Table,
    Button,
    Form,
    Select,
    Spin,
    Tooltip, Tag, Popover,
} from 'antd';
import {FileTextOutlined,FolderOutlined} from '@ant-design/icons';
import {action, flushSubscribeList, openStatus} from "../../store/action";
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css'
import API from '../../api/api'
import {FormForFile,FormForModule} from '../Modal/InsertModalContent'
import {ModuleUpdate,FileUpdate} from '../Modal/UpdateModalContent'
import {Link} from "react-router-dom";
import IconFont6 from "../../util/autoIcon/folder";
import LayoutManage from "../Layout/LayoutManage";
import MoveModuleAndFile from "../Modal/MoveModuleAndFile";
import IconFont17 from "../../util/autoIcon/correct";
import IconFont16 from "../../util/autoIcon/error";
import judgeFileType from "../../service/judgeFileType";
import './ModuleManage.css'

const { Option } = Select;
//
// // Modal實現拖動效果
// class BuildTitle extends React.Component {
//     updateTransform = transformStr => {
//         this.modalDom.style.transform = transformStr;
//     };
//     componentDidMount() {
//         this.modalDom = document.getElementsByClassName(
//             "ant-modal-wrap" //modal的class是ant-modal-wrap
//         )[0];
//     }
//     render() {
//         const { title } = this.props;
//         return (
//             <DragM updateTransform={this.updateTransform}>
//                 <div>{ title }</div>
//             </DragM>
//         );
//     }
// }

let config = require('../../util/config').config

export default class ModuleManage extends React.Component{
    formRef = React.createRef();
    constructor(props) {
        super(props);
        this.state = {
            hasSpined:false,
            spinStatus:false,
            moduleType:"all",
            layout:{
                LAYOUT_TYPE:null,
                LAYOUT_ID:null
            },
            visible:false,
            moduleInsertType:null,
            loading:false,
            status:true,
            data : [],
            selectedRowKeys: [], // Check here to configure the default column
            moveVisible:false,
            moduleInsertVisible:false,
            moduleUpdateVisible:false,
            moduleContentVisible:false,
            layoutManageVisible:false,
            fileInsertVisible:false,
            fileUpdateVisible:false,
            fileContent:null,
            fileList:[],
            name: null,
            type: null,
            // columns: this.columns
        };

        //从match拿到的参数 例如：file&9 / folder&1 / folder-f&2
        this.params = this.props.match.params.id.split("&");
        this.getManageFlag(this.params)
        this.storeFresh("receiveProps");
    }

    layoutParams = null
    //      layoutParams参数格式示例
    //      {
    //          LAYOUT_TYPE:"3",
    //          LAYOUT_ID:1,
    //          PARAMS:{
    //              width_1:null,
    //              width_2:null,
    //              //  布局3（基于布局2参数，添加了下面新参数）
    //              height_1:null,
    //              height_3:null,
    //              width_3:null,
    //              //  布局4（基于布局2、3参数，添加了下面新参数）
    //              width_4:null,
    //              height_4:null
    //          }
    //      }


    //经过增删改后是否刷新，注意没有查，查会调用路由来实现
    status = false;

    //判断用户管理级别，只有super级别可以在模块管理下创建直属菜单，manage只能在直属菜单下创建子菜单
    userType = null;

    //判断manage用户是否可以管理该菜单，true可以，false只能访问
    flag = null;

    //能管理的modules
    getManageModule = [];

    //路由传的参数，
    params = []

    data = [];

    //是否拥有管理权
    manageFlag = null;

    text = config.is_delete;

    autoColumns = [];

    content = null;

    columns = [
        {
            title: null,
            dataIndex: 'name',
            key: 'name',
            width: 200,
            // fixed: 'left',
            ellipsis:true,
            render: (text, record) => {
                let type;
                if(this.props.linkType=="userPage"){
                    // 1、判断 record.type是否为 config.folder_d 、config.file_d 或者 config.folder
                    if(record.type == config.folder){
                        return(
                            <Tooltip placement="topLeft" title={text}>
                                <Link to={`/eip/table/folder&${record.key}`}><IconFont6 type="icon-huabanfuben"/>&nbsp;&nbsp;{text}</Link>
                            </Tooltip>
                                )
                    }else {
                        if(record.type==config.article){
                            type = "article"
                            return (
                                <Tooltip placement="topLeft" title={text}>
                                    <Link to={`/eip/file/${type}/${record.key}`}>{text}</Link>
                                </Tooltip>
                            )
                        }else {
                            type = "file"
                            return (
                                <Tooltip placement="topLeft" title={text}>
                                    <a onClick={_=>{API.downloadFile(record.key)}}>{judgeFileType(text)}&nbsp;&nbsp;{text}</a>
                                </Tooltip>
                            )

                        }
                    }
                }else {
                    // 1、判断 record.type是否为 config.folder_d 、config.file_d 或者 config.folder
                    if(record.type == config.folder_d || record.type == config.article_d || record.type == config.file_d || record.type == config.folder || record.type == config.page){
                        if(record.type == config.folder_d){
                            type = "folder";
                        }else if(record.type == config.article_d){
                            type = "article"
                        }else if(record.type == config.file_d){
                            type = "file"
                        }else if(record.type == config.page){
                            type = "page"
                        }else {
                            type = "folder-f"
                        }
                        let wrapper = type+"&"+record.key
                        // this.setState({status:true})
                        action(wrapper)
                        // pushUrl(moduleManage_url+wrapper)
                        return (
                            <Tooltip placement="topLeft" title={text}>
                                <Link to={`/eip/module-manage/${type}&${record.key}`} >{type=="file" || type=="article" || type=="page"? <FileTextOutlined/> : (type=="folder" ? <FolderOutlined/> : (type == "folder-f"?<IconFont6 type="icon-huabanfuben"/>:null))}&nbsp;&nbsp;{text}</Link>
                            </Tooltip>
                        )
                    }
                    else if(record.type == config.file || record.type == config.article){
                        if(record.type==config.article){
                            console.log("record.key",record.key)
                            return (
                                <Tooltip placement="topLeft" title={text}>
                                    <a onClick={_=>{this.getFileContent(record.key,record.type)}}>{text}</a>
                                </Tooltip>
                            )
                        }else if(record.type==config.file){
                            return (
                                <Tooltip placement="topLeft" title={text}>
                                    {/*<a onClick={_=>{this.getFileContent(record.key,record.type)}}>{judgeFileType(text)}&nbsp;&nbsp;{text}</a>*/}
                                    <a onClick={_=>{API.downloadFile(record.key)}}>{judgeFileType(text)}&nbsp;&nbsp;{text}</a>
                                </Tooltip>
                            )
                        }
                    }
                }
            }
        },
        {
            title: null,
            dataIndex: 'type',
            key: 'type',
            // ellipsis:true,
            width: 50
        },
        {
            title: "权限",
            dataIndex: 'moduleManage',
            key: 'moduleManage',
            filterDropdownVisible:false,
            width: 50,
            render:(text,record)=>{
                if(record.moduleManage=="true"){
                    return <IconFont17 type="icon-icon-test-copy-copy"/>
                }else if(record.moduleManage=="false"){
                    return <IconFont16 type="icon-cuowu"/>
                }else if(record.type==config.folder || record.type==config.file || record.type==config.article){
                    return <IconFont17 type="icon-icon-test-copy-copy"/>
                }
            }
        }

    ]

    columnsForFile = [
        {
            title: "建立人",
            dataIndex: 'createUser',
            key: 'updateUser',
            width: 110,
            ellipsis:true,
        },
        {
            title: "建立时间",
            dataIndex: 'createTime',
            key: 'updateTime',
            width: 100,
            ellipsis:true,
        },
        {
            title: "修改人",
            dataIndex: 'updateUser',
            key: 'updateUser',
            width: 110,
            ellipsis:true,
        },
        {
            title: "修改时间",
            dataIndex: 'updateTime',
            key: 'updateTime',
            width: 100,
            ellipsis:true,
        },
        {
            title: "状态",
            dataIndex: 'status',
            key: 'status',
            width:40,
            // fixed: 'right',
            // ellipsis:true,
            render:(text,record) => {
                return (
                    <span>
                        {this.isTop(text)}
                        {this.isNotify(record)}
                    </span>
                )
            }
        },
    ]

    columnsForModule = [
        {
            title: '操作',
            width:150,
            key: 'Options',
            // fixed: 'right',
            ellipsis:true,
            render: (text, record) => (
                <div>
                    {
                        record.moduleManage=="true" || record.type==config.folder || record.type==config.file || record.type==config.article ?
                            <>
                                {/*<Button type="primary" shape="round" size="middle" onClick={_=>{this.move(record)}} style={{marginRight:"0.5rem",backgroundColor:"#a0a8af",border:"none"}}>*/}
                                {/*    订阅*/}
                                {/*</Button>*/}
                                <Button type="primary" shape="round" size="middle" onClick={_=>{this.update(record)}} style={{marginRight:"0.5rem"}}>
                                    修改
                                </Button>
                                <Button type="primary" shape="round" size="middle" onClick={_=>{this.move(record)}} style={{border: "none", marginRight: "0.5rem", backgroundColor: "#55c68d"}}>
                                    移动
                                </Button>
                                <Popconfirm placement="right" title={this.text} onConfirm={_=>{this.delete(record)}} okText="确定" cancelText="取消">
                                    <Button type="primary" shape="round" style={{marginRight: "1rem", border: "0.1rem solid #ff7875"}} danger>
                                        删除
                                    </Button>
                                </Popconfirm>
                            </>
                            :
                            null

                    }

                </div>
            ),
        }
    ]

    isTop = (text)=>{
        if(text=="Y"){
            return <Tag color="#f50">{config.top_status}</Tag>
        }
    }

    isNotify = (record)=>{
        let currentDate = new Date()
        let date = new Date(record.updateTime);
        if(record.new!="" && record.new!=null){
            date.setDate(date.getDate()+Number.parseInt(record.new));
            if(currentDate<=date){
                return <Tag color="#87d068">{config.new_notify}</Tag>
            }
        }
    }

    //render调用接口获取当前的folder-d绑定的布局类型，再将布局值返回给 layoutType
    layoutType=null;

    getFileContent=(key,type)=>{
        let item = API.getFileContent(key,type);
        if(type==config.article){
            this.setState({fileContent:item.articleContent})
            this.setState({fileList:item.urls})
        }else if(type==config.file){
            this.setState({fileList:item})
        }
        this.setState({
            fileType:type,
            moduleContentVisible:true
        })
    }

    UNSAFE_componentWillReceiveProps(nextProps, nextContext) {
        this.state.moduleType="all";
        this.state.spinStatus=false;
        this.state.hasSpined=false;
        //从match拿到的参数 例如：file&9 / folder&1 / folder-f&2
        this.params = nextProps.match.params.id.split("&");
        // console.log("UNSAFE_componentWillReceiveProps"+"。。。"+nextProps.match.params.id)
        this.getManageFlag(this.params);
        this.storeFresh("receiveProps");
        if(this.formRef.current!=null){
            this.flushForm()
        }
    }

    //是否显示管理按钮的标记
    getManageFlag=(params)=>{
        let manageModuleArr = JSON.parse(sessionStorage.getItem("getManageModule"))
        if(params[0]=="folder" && params[1]==0 ){
            if(localStorage.getItem("userType")=="manager"){
                this.manageFlag=false
            }else if(localStorage.getItem("userType")=="super"){
                this.manageFlag=true
            }
        }else if(params[0]!="folder-f"){
            if(manageModuleArr instanceof Array && manageModuleArr.length>0){
                let item = manageModuleArr.filter(item=>item.moduleId==params[1])[0]
                if(item.moduleManage=="true"){
                    this.manageFlag=true
                }else {
                    this.manageFlag=false
                }
            }else this.manageFlag=false
        }
    }

    //路由跳转执行此函数刷新表内数据
    storeFresh(method){
        let tmpData = [];
        //获取最新的getManageModule
        this.getManageModule = JSON.parse(sessionStorage.getItem("getManageModule"))
        //如果触发的是菜单,子菜单对象个数是0,1或者多个，并把个数赋值给tmpDate数组
        if(this.params[0] == "folder"){
            if(this.state.moduleType=="all"){
                tmpData= this.getManageModule.filter(item => item.moduleParentId == this.params[1])
            }else{
                tmpData= this.getManageModule.filter(item => item.moduleParentId == this.params[1] && item.moduleType == this.state.moduleType)
            }
            console.log("Component ModulePage ModuleManage tmpData:",tmpData)
            // this.setState({name:"目录名称",type:"目录类型"})
            // this.columns[0].title = "菜单/文件库/文章库名称";
            this.columns[1].title = "类型";
            let tmpColumns = this.columns;
            tmpColumns[0].width = 300
            tmpColumns[1].width = 150
            tmpColumns[2].width = 150
            let tmpColumnsForModule = this.columnsForModule
            tmpColumnsForModule[0].width = 200
            this.autoColumns = tmpColumns.concat({
                    title:"排序",
                    dataIndex: 'sortNum',
                    key:'sortNum',
                    width: 150
                },
                {
                    title:"布局",
                    dataIndex: 'layoutType',
                    key:'layoutType',
                    width: 150
                },
                {
                    title:"区域",
                    dataIndex: 'layoutArea',
                    key:'layoutArea',
                    width: 150
                }).concat(tmpColumnsForModule)
            this.pushData(tmpData,method)
        }
        //如果触发的是 file-d 或者 folder-f，里面所属的文件对象个数是0,1或者多个，并把个数赋值给tmpDate数组
        else if(this.params[0] == "article" || this.params[0] == "file" || this.params[0] == "folder-f"){
            let type = null;
            if(this.params[0] == "folder-f"){
                type = "folder"
            }
            else if(this.params[0] == "file"){
                type = "file-d"
            }
            else if(this.params[0] == "article"){
                type = "article-d"
            }
            let result = API.getFiles(this.params[1],type);
            tmpData = result.getFile;
            this.manageFlag=result.manageFlag
            console.log("tmpData",tmpData)
            // this.setState({name:"文件名称",type:"文件类型"})
            this.columns[0].title = "文件名称";
            this.columns[1].title = "类型";
            let tmpColumns = this.columns;
            tmpColumns[0].width = 240;
            tmpColumns[1].width = 50
            tmpColumns[2].width = 50;
            let tmpColumnsForModule = this.columnsForModule
            tmpColumnsForModule[0].width = 150
            this.autoColumns = tmpColumns.concat(this.columnsForFile).concat(tmpColumnsForModule)
            this.pushFileData(tmpData,method)
        }
    }

    //通过storeFresh()判断store的数据是否为folder，如果是执行pushData()
    pushData(tmpData,method){
        let localData = [];
        for (let i = 0; i <tmpData.length ; i++) {
            let node = tmpData[i];
            let type;
            if(node.moduleType=="folder-d"){
                type = config.folder_d
            }else if(node.moduleType=="article-d"){
                type = config.article_d
            }
            else if(node.moduleType=="file-d"){
                type = config.file_d
            }
            else if(node.moduleType == "page"){
                type = config.page
            }
            localData.push({
                new: node.new,
                key: node.moduleId,
                moduleManage: node.moduleManage,
                parentId: node.moduleParentId,
                name: node.moduleName,
                sortNum: node.sortNum,
                type: type,
                layoutType:node.layoutType,
                layoutArea:node.layoutArea
            });
        }
        if(method=="receiveProps"){
            this.state.data = localData;
        }else if(method=="setState"){
            this.state.data = localData;
            this.setState({
                spinStatus:false,
                hasSpined:false
            })
        }
    }

    //通过storeFresh()判断store的数据是否为file，是则执行pushFileData()
    pushFileData(tmpData,method){
        let localData = [];
        for (let i = 0; i <tmpData.length ; i++) {
            let node = tmpData[i];
            let id = node.fileId;
            let name = node.fileName;
            let status = node.status;
            let createUser = node.createUser;
            let createTime = node.createTime;
            let updateUser = node.updateUser;
            let updateTime = node.updateTime;
            let type;
            if(node.fileType == "file"){
                type = config.file
            }
            else if(node.fileType == "article"){
                type = config.article
            } else {
                type = config.folder
            }
            localData.push({
                new: node.new,
                key: id,
                name: name,
                type: type,
                status: status,
                createUser:createUser,
                createTime:createTime,
                updateUser:updateUser,
                updateTime:updateTime
            });
        }
        if(method=="receiveProps"){
            this.state.data = localData;
        }else if(method=="setState"){
            this.setState({data:localData})
        }
    }

    insert = (type) =>{
        // store的closeStatus在此失效
        // closeStatus();
        this.status = false
        this.setState({
            moduleInsertVisible:true,
            //type: folder-d file-d article-d
            moduleInsertType:type
        })
        this.setState({
            visible:false
        })
    }

    cancel = () => {
        this.setState({
            selectedRowKeys: [],
            loading: false
        });
    };

    delete=(record)=>{
        let status = null;
        //如果是在菜单下做删除，删除的列表数据有 folder-d 和 file-d
        if(this.params[0]=="folder"){
            if(record.type==config.folder_d){
                record.type = "folder-d"
            }else if(record.type==config.file_d){
                record.type = "file-d"
            }else if(record.type==config.article_d){
                record.type = "article-d"
            }else if(record.type==config.page){
                record.type = "page"
            }
            status = API.deleteBatchItems([{FILE_ID:record.key,FILE_TYPE:record.type}])
            if(status == "ok"){
                if(API.loginToken()=="ok"){
                    //如果返回ok,刷新一下
                    this.storeFresh("setState")
                    //因为frame组件侧边栏也要显示最新页面，因此要发送给redux更新提示
                    openStatus()
                }
            }
        }
        //如果是在资料库下或者文件夹下做删除,删除的列表数据有 file、article和folder
        else if(this.params[0]=="article" || this.params[0]=="file" || this.params[0]=="folder-f"){
            if(record.type==config.file){
                record.type = "file"
            }else if(record.type==config.article){
                record.type = "article"
            }else if(record.type==config.folder){
                record.type = "folder"
            }
            status = API.deleteBatchItems([{FILE_ID:record.key,FILE_TYPE:record.type}])
            if(status == "ok"){
                //如果返回ok,刷新一下
                this.storeFresh("setState")
            }
        }
    }

    deleteSelected =()=>{
        console.log("Component ModulePage ModuleManage deleteSelected() this.state.selectedRowKeys",this.state.data)
        let deleteArr = []
        //在this.state.data中为selectedRowKys匹配type
        //对this.state.data作遍历
        for(let i=0;i<this.state.data.length;i++){
            //再对this.state.selectedRowKeys作遍历
            for(let k=0;k<this.state.selectedRowKeys.length;k++){
                //如果this.state.selectedRowKeys[k]找到了this.state.data[i].key,就把this.state.data[i].type找出来，作为{FILE_ID,FILE_TYPE}对象push到deleteArr数组中
                if(this.state.selectedRowKeys[k] == this.state.data[i].key){
                    let type = null;
                    let id = null;
                    id = this.state.data[i].key
                    type = this.matchType(this.state.data[i].type)
                    deleteArr.push({FILE_ID:id,FILE_TYPE:type})
                    break;
                }
            }
        }
        console.log("Component ModulePage ModuleManage deleteSelected() deleteArr",deleteArr)
        // console.log("Component ModulePage ModuleManage deleteSelected()",deleteArr)
        if(API.deleteBatchItems(deleteArr)=="ok"){
            //如果删除成了，刷新
            if(API.loginToken()=="ok"){
                this.storeFresh("setState")
                //如果是在菜单下面执行的删除命令，那么src/page/frame/Index组件也要刷新一下，需要调用redux
                if(this.params[0]=="folder"){
                    openStatus()
                }
            }
        }
    }
    //输入record.type的中文格式，自动转换成要发送的英文格式
    matchType(type){
        if(type==config.folder_d){
            type="folder-d"
        }else if(type==config.file_d){
            type="file-d"
        }else if(type==config.article_d){
            type = "article-d"
        }else if(type==config.page){
            type = "page"
        }else if(type==config.file){
            type = "file"
        }else if(type==config.article){
            type = "article"
        }else if(type==config.folder){
            type = "folder"
        }
        return type
    }

    move = (record)=>{
        console.log(record)
        this.setState({moveVisible:true})
        this.status = false
        let type = null;
        if(record.type==config.folder_d){
            type = "folder-d"
        }else if(record.type == config.article_d){
            type = "article-d"
        }else if(record.type==config.file_d){
            type = "file-d"
        }else if(record.type==config.page){
            type = "page"
        }else if(record.type==config.file){
            type = "file"
        }else if(record.type==config.article){
            type = "article"
        }else if(record.type==config.folder){
            type = "folder"
        }
        this.moveDataRenderTree = API.getDatasForMove(type)
        this.moveNode = record
        console.log("this.moveDataRenderTree:",this.moveDataRenderTree)
    }

    update = (record) => {
        this.data=record
        const urlNodeList = sessionStorage.getItem("routePath").split("/")
        const parentData = urlNodeList[urlNodeList.length-1].split("&")
        if(parentData[0]=="folder"){
            parentData[0]= "folder-d"
        }else if(parentData[0]=="file"){
            parentData[0]= "file-d"
        }else if(parentData[0]=="article"){
            parentData[0]= "article-d"
        }else if(parentData[0]=="folder-f"){
            parentData[0]= "folder"
        }
        this.data.parentType = parentData[0]
        this.data.parentId = parentData[1]
        this.setState({visible:false})
        // closeStatus()
        this.status = false
        // sessionStorage.setItem("index",JSON.stringify(record))
        this.setState({moduleUpdateVisible:true})
        if(record.type==config.page){
            this.pageInfo = API.getModuleDetail(record.key)
        }
    }

    onSelectChange = selectedRowKeys => {
        // closeStatus()
        console.log('selectedRowKeys changed: ', selectedRowKeys);
        this.setState({ selectedRowKeys });
    };

    handleModalForInsert = () => {
        //如果负责新增的子组件成功插入值，成功提交，那么本组件的status值置为true
        if(this.status==true){
            //如果是true 刷新module,adminModule,manageModule，刷新成功返回"ok","error"
            let status = API.loginToken();
            //如果loginToken刷新成功，此组件再进行列表里面的数据刷新
            if(status=='ok'){
                this.storeFresh("setState")
                this.status=false
            }
        }
        if(this.params[0]=="folder"){
            //如果是在菜单下面执行的删除命令，那么src/page/frame/Index组件也要刷新一下，需要调用redux
            openStatus()
        }
        this.setState({
            layoutManageVisible:false,
            moveVisible:false,
            moduleInsertVisible: false,
            moduleUpdateVisible: false,
        });
    };

    handleModalForUpdate=()=>{
        this.handleModalForInsert();
    }

    handleForMove=()=>{
        this.handleModalForInsert();
    }

    handleModalForDetail=()=>{
        this.setState({ moduleContentVisible: false });
    }

    result=(status)=>{
        this.status = status
    }

    layoutManage=()=>{
        this.setState({layoutManageVisible:true})
    }

    closeLayoutManage=()=>{
        this.handleModalForInsert()
    }

    getContent = ()=>{
        if(this.params[0]=="folder"&&this.params[1]=="0"){
            this.content = (
                <div>
                    <p style={{cursor:"pointer"}} onClick={_=>{this.insert("folder-d")}}>添加菜单</p>
                </div>
            )
        }else {
            this.content = (
                <div>
                    <p style={{cursor:"pointer"}} onClick={_=>{this.insert("folder-d")}}>添加{config.folder_d}</p>
                    <p style={{cursor:"pointer"}} onClick={_=>{this.insert("file-d")}}>添加{config.file_d}</p>
                    <p style={{cursor:"pointer"}} onClick={_=>{this.insert("article-d")}}>添加{config.article_d}</p>
                    <p style={{cursor:"pointer"}} onClick={_=>{this.insert("page")}}>添加{config.page}</p>
                </div>
            )
        }
    }

    addFile=()=> {
        this.setState({
            moduleInsertVisible:true
        })
    }

    getLayout=()=> {
        if(this.params[0]=="folder" && this.params[1]!="0"){
            this.layoutParams=API.getLayout("folder-d",this.params[1]);
        }
    }

    addRootModule=()=> {
        this.insert("folder-d")
    }


    flushForm() {
        this.formRef.current.resetFields();
    }

    getTableModuleName(){
        if(this.state.moduleType=="folder-d"){
            this.columns[0].title = "菜单名称";
        }else if(this.state.moduleType=="file-d"){
            this.columns[0].title = "文件库名称";
        }else if(this.state.moduleType=="article-d"){
            this.columns[0].title = "文章库名称";
        }else {
            this.columns[0].title = "名称";
        }
    }

    //计数器
    count = 0

    getLayoutList(){
        if(this.params[0]=="folder"){
            let flush = false;
            let clientArr = this.state.data
            let serverArr = []
            // if(this.state.moduleType==null){
            //     serverArr = API.getLayoutList("folder-d",this.params[1],"all")
            // }else {
            //     serverArr = API.getLayoutList("folder-d",this.params[1],this.state.moduleType)
            // }
            serverArr = API.getLayoutList("folder-d",this.params[1],this.state.moduleType)
            if(clientArr.length==serverArr.length){
                a:for(let i=0;i<serverArr.length;i++){
                    for(let j=0;j<clientArr.length;j++){
                        if(serverArr[i].MODULE_ID==clientArr[j].key){
                            break
                        }else if(j==clientArr.length-1){
                            flush=true;
                            break a;
                        }
                    }
                }
                if(flush){
                    this.flushNewData()
                }else {
                    a:for(let k=0;k<serverArr.length;k++){
                        for(let l=0;l<clientArr.length;l++){
                            if(clientArr[l].key==serverArr[k].MODULE_ID){
                                clientArr[l].layoutId=serverArr[k].LAYOUT_ID
                                clientArr[l].layoutType=serverArr[k].LAYOUT_TYPE
                                clientArr[l].layoutArea=serverArr[k].LAYOUT_AREA
                            }
                        }
                    }
                    this.setState({
                        data:clientArr,
                        hasSpined:true,
                        spinStatus:false
                    })
                }
            }else {
                this.flushNewData()
            }
            console.log("clientArr",clientArr)
        }

    }

    flushNewData = () =>{
        if(this.count<3){
            API.loginToken()
            openStatus()
            ++this.count
            this.getLayoutList()
        }else {
            this.count=0
            alert("数据无法同步")
        }
    }

    changeSubscribeStatus(value){
        let type = value.type
        let id = value.id
        let status;
        if(sessionStorage.getItem("subStatus")=="true"){
            status = API.cancelSub({type:type,id:id})
        }else if(sessionStorage.getItem("subStatus")=="false"){
            status = API.submitSub({type:type,id:id})
        }
        if(status=="ok"){
            this.setState({})
        }
    }

    render() {
        // if(!this.state.spinStatus && !this.state.hasSpined && this.params[0]=="folder"){
        //     this.setState({
        //         spinStatus:true
        //     },()=>{
        //         setTimeout(()=>this.getLayoutList(),200)
        //     })
        // }
        //获取table的头部字段（菜单名称、文件库名称、文章库名称）
        // alert("ModuleManage:"+this.props.match.params.id)
        this.getTableModuleName();
        //获取布局参数
        this.getLayout();
        this.getContent();
        let selectedLabel
        if(this.params[0]=="folder"&&this.params[1]!="0"){
            selectedLabel = `布局 ${this.layoutParams.LAYOUT_TYPE}`
        }else if(this.params[0]=="page"){

        }
        const {selectedRowKeys} = this.state;
        const rowSelection = {
            selectedRowKeys,
            onChange: this.onSelectChange,
        };
        const hasSelected = selectedRowKeys.length > 0;
        let moduleContent = null;
        if(this.params[0]=="page"){
            moduleContent = API.getModuleDetail(this.params[1])[0].MODULE_CONTENT
        }
        let subStatus;
        if(this.params[0]=="file" || this.params[0]=="article" || this.params[0]=="folder-f"){
            subStatus = API.subStatus({
                type:this.params[0]=="file"?"file-d":this.params[0]=="article"?"article-d":this.params[0]=="folder-f"?"folder":null,
                id:this.params[1]
            })
            sessionStorage.setItem("subStatus",subStatus)
        }
        return this.params[0]=="page"
                    ?
                    <div style={{marginRight:"1rem"}} id="moduleContent-page" dangerouslySetInnerHTML={{__html:moduleContent}}></div>
                    :
                    <Spin spinning={false} tip="loading">
                        <div>
                            <div style={{marginBottom:"1rem" }}>
                                    {this.manageFlag == true || this.manageFlag == "true"
                                    ?
                                    <>
                                        {
                                            this.params[0]=="folder"
                                                ?
                                                (this.params[1]!="0"
                                                        ?
                                                        <Popover  visible={this.state.visible} onVisibleChange={event=>event==false&&this.state.moduleInsertVisible==true?null:this.setState({visible:!this.state.visible})} id="addModule" placement="rightTop" content={this.content} trigger="click">
                                                            <Button type="primary" style={{marginRight:"0.5rem"}}>添加</Button>
                                                        </Popover>
                                                        :
                                                        <Button style={{marginRight:"0.5rem"}} type="primary" onClick={this.addRootModule}>添加</Button>
                                                )
                                                :
                                                (
                                                    this.params[0]=="file" || this.params[0]=="article" || this.params[0]=="folder-f"
                                                        ?
                                                        <Button style={{marginRight:"0.5rem"}} type="primary" onClick={this.addFile}>添加</Button>
                                                        :
                                                        null
                                                )
                                        }
                                        <Button type="danger" style={{marginRight:"0.5rem"}} onClick={this.deleteSelected} disabled={!hasSelected}>删除选中</Button>
                                        <Button type="primary" onClick={this.cancel} disabled={!hasSelected}>取消</Button>
                                        {
                                            this.params[0]=="file" || this.params[0]=="article" || this.params[0]=="folder-f"?
                                                <Form
                                                    style={{display:"inline",marginLeft:"1rem"}}
                                                    layout={"inline"}
                                                >
                                                    <Form.Item
                                                        name="subscribe"
                                                        label="訂閱管理"
                                                        style={{display:"inline"}}
                                                    >
                                                        <Button type={subStatus=="true"?"danger":"primary"} onClick={()=>{this.changeSubscribeStatus({
                                                            type:this.params[0]=="file"?"file-d":this.params[0]=="article"?"article-d":this.params[0]=="folder-f"?"folder":null,
                                                            id:this.params[1] })}}
                                                        >
                                                            {subStatus=="true"?"取消訂閱":"訂閱"}
                                                        </Button>
                                                    </Form.Item>
                                                </Form>
                                                :
                                                null
                                        }
                                    </>
                                    :
                                    null
                                }
                                {this.params[0]=="folder"&&this.params[1]!="0"
                                    ?
                                    <Form
                                        style={{display:"inline",marginLeft:"1rem"}}
                                        layout={"inline"}
                                        onReset={this.onReset}
                                        ref={this.formRef}
                                    >
                                        {
                                            this.manageFlag==true?
                                                <Form.Item
                                                    name="layout"
                                                    label="布局管理"
                                                    style={{display:"inline"}}
                                                >
                                                    <Button type="primary" onClick={this.layoutManage} >
                                                        {selectedLabel}
                                                    </Button>
                                                </Form.Item>
                                                :
                                                <Form.Item
                                                    name="layout"
                                                    label="当前布局"
                                                    style={{display:"inline"}}
                                                >
                                                    <Button type="primary" >
                                                        {selectedLabel}
                                                    </Button>
                                                </Form.Item>
                                        }
                                        <Form.Item
                                            name="moduleType"
                                            label="列表类型"
                                            style={{display:"inline"}}
                                        >
                                            <Select defaultValue={this.state.moduleType} style={{ width: 120 }} allowClear onSelect={item=>{
                                                this.state.moduleType=item;
                                                this.storeFresh("setState")
                                            }}>
                                                <Option key="0" value="all">所有</Option>
                                                <Option key="1" value="folder-d">{config.folder_d}</Option>
                                                <Option key="2" value="file-d">{config.file_d}</Option>
                                                <Option key="3" value="article-d">{config.article_d}</Option>
                                                <Option key="4" value="page">{config.page}</Option>
                                            </Select>
                                        </Form.Item>
                                    </Form>
                                    :
                                    null
                                }
                                {/*<span style={{ marginLeft: 8 }}>*/}
                                {/*    {hasSelected ? `Selected ${selectedRowKeys.length} items` : ''}*/}
                                {/*</span>*/}
                            </div>
                            <Table className={this.props.linkType=="userPage"?null:"decorate"} size={"middle"} rowSelection={rowSelection} columns={this.autoColumns} dataSource={this.state.data} scroll={{x: 1500}}/>
                            {/*{hasSelected ? null : this.storeFresh(rowSelection)}*/}
                            {/*modal提供新增界面，展示新增的栏位*/}
                            <Modal visible={this.state.moveVisible}
                                   title="移动"
                                   onCancel={this.handleForMove}
                                   footer={[
                                       <Button key="back" onClick={this.handleForMove}>退出</Button>
                                   ]}
                                   width={1000}
                                   destroyOnClose
                            >
                                <MoveModuleAndFile  layoutParams={this.layoutParams} result={this.result} moveNode={this.moveNode} moveDataRenderTree={this.moveDataRenderTree}/>
                            </Modal>
                            <Modal visible={this.state.layoutManageVisible}
                                   title="布局管理"
                                   onCancel={this.closeLayoutManage}
                                   footer={[
                                       <Button key="back" onClick={this.closeLayoutManage}>退出</Button>
                                   ]}
                                   width={1000}
                                   destroyOnClose
                            >
                                <LayoutManage layoutParams={this.layoutParams} result={this.result}  showCommit={true} data={this.params}></LayoutManage>
                            </Modal>
                            <Modal visible={this.state.moduleInsertVisible}
                                   title={this.params[0]=="folder" ? (this.state.moduleInsertType=="folder-d"?`添加${config.folder_d}`:this.state.moduleInsertType=="file-d"?`添加${config.file_d}`: this.state.moduleInsertType =="article-d"?`添加${config.article_d}`:this.state.moduleInsertType=="page"?`添加${config.page}`:null) : (this.params[0]=="file" || this.params[0]=="folder-f"? `添加${config.file}/${config.folder}` : `添加${config.article}` )}
                                   onCancel={this.handleModalForInsert}
                                   footer={[
                                       <Button key="back" onClick={this.handleModalForInsert}>退出</Button>
                                   ]}
                                   width={1000}
                                   destroyOnClose
                            >
                                {this.params[0]=="folder" ? <FormForModule type={this.state.moduleInsertType} layoutParams={this.layoutParams} result={this.result} data={this.params}></FormForModule> : <FormForFile result={this.result} data={this.params}></FormForFile>}
                            </Modal>
                            {/*modal提供修改界面，展示修改的栏位*/}
                            <Modal visible={this.state.moduleUpdateVisible}
                                   title={this.data.type==config.folder_d ? "修改菜单" : (this.data.type==config.file_d? "修改文件库" : (this.data.type==config.article_d ? "修改文章库" : (this.data.type==config.page ?  `修改${config.page}`:(this.data.type==config.folder?"修改文件夹":(this.data.type==config.file?"修改文件":(this.data.type==config.article?"修改文章":null))))) )}
                                   onCancel={this.handleModalForUpdate}
                                   footer={[
                                       <Button key="back" onClick={this.handleModalForUpdate}>退出</Button>
                                   ]}
                                   width={1000}
                                   destroyOnClose
                            >
                                {this.params[0]=="folder" ? <ModuleUpdate pageInfo={this.pageInfo} layoutParams={this.layoutParams} result={this.result} defaultData = {this.data}/> : <FileUpdate result={this.result} defaultData = {this.data}/>}
                            </Modal>
                            {/*modal提供详情内容，比如文章的内容，文件的内容*/}
                            <Modal visible={this.state.moduleContentVisible}
                                   title="详情"
                                   onCancel={this.handleModalForDetail}
                                   footer={[
                                       <Button key="back" onClick={this.handleModalForDetail}>退出</Button>
                                   ]}
                                   width={1000}
                                   destroyOnClose
                            >
                                {this.state.fileType==config.article ?
                                    <div style={{maxHeight:"600px",overflow:"auto"}}>
                                        <div dangerouslySetInnerHTML={{__html:this.state.fileContent}} />
                                    </div>
                                    :
                                    null
                                }
                                {this.state.fileList.length>0?
                                    <List
                                        itemLayout="horizontal"
                                        dataSource={this.state.fileList}
                                        renderItem={item => (
                                            <List.Item>
                                                <List.Item.Meta
                                                    avatar={<Avatar src={item.response} />}
                                                    title={<a target="_blank" href={item.response}>{item.name}</a>}
                                                />
                                            </List.Item>
                                        )}
                                    />
                                    :
                                    null
                                }
                            </Modal>
                        </div>
                    </Spin>
    }


}








